import qs from 'qs'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import store from '@/store'

// 新建axios 实例
const REQ_BASE_URL = process.env.VUE_APP_BASE_URL

const request = axios.create({
  baseURL: REQ_BASE_URL,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  },
  timeout: 100000,
})

// 请求拦截
request.interceptors.request.use(
  config => {
    const { headers, params, data } = config
    config.params = {
      ...(params || {}),
    }
    if (process.env.NODE_ENV === 'development') {
      config.params._t = getToken()
    }
    if (headers['Content-Type'].includes('multipart/form-data')) {
      if (data) {
        data.append('_t', getToken())
      }
      config.data = data
    } else {
      const newData = {
        ...(data || {}),
        _t: getToken(),
      }
      config.data = qs.stringify(newData)
    }
    return config
  },
  error => {
    console.log('request-interceptors', error) // for debug
    return Promise.reject(error)
  },
)

// 响应拦截
request.interceptors.response.use(
  response => {
    const { data, status, config } = response

    if (config?.responseType === 'blob') {
      const url = window.URL.createObjectURL(data)
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } else {
      return Promise.resolve({ code: 0, data })
    }
  },
  error => {
    const response = error.response
    const resData = response?.data ?? {}

    if (resData == 'not login' || resData == '账户已禁用') {
      store.dispatch('app/logout')
    } else {
      Message.error(resData?.ErrMsg ?? resData ?? '网关错误')
    }
    return Promise.resolve({})
  },
)

export default request
